/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package org.dusin.teachassist.matchalg;

/**
 *使用公共最长字符串来计算匹配度
 * @author dusin
 */
public class MaxSubString implements MatchStrategy{

    @Override
    public double getMatchDegree(String a, String b) {
        double result;
        int length = getMatchLength(a,b);
        result = length/(double)a.length();
        return result;
    }
    @Override
    public int getMatchLength(String a, String b) {
        
        // 参数检查
        if (a == null || b == null) {
            return 0;
        }
        if (a.equals("") || b.equals("")) {
            return 0;
        }
        // 二者中较长的字符串
        String max = "";
        // 二者中较短的字符串
        String min = "";
        if (a.length() < b.length()) {
            max = b;
            min = a;
        } else {
            max = b;
            min = a;
        }
        String current = "";
        // 遍历较短的字符串，并依次减少短字符串的字符数量，判断长字符是否包含该子串
        for (int i = 0; i < min.length(); i++) {
            for (int begin = 0, end = min.length() - i; end <= min.length(); begin++, end++) {
                current = min.substring(begin, end);
                if (max.contains(current)) {
                    return current.length();
                }
            }
        }        
        return 0;
    }
}
